//
//  SeparateDetailsViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/8/14.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "SeparateDetailsViewController.h"
#import "EditShopSectionsView.h"
#import "SeparatePlanViewController.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "MeatShopSectionModel.h"
#import "MeatShopRightModel.h"
#import "SeparateDetailsCell.h"
#import "SeparateContentCell.h"

#import "EditShopBox.h"

#define  rightCellIdentifier @"rightCellIdentifier"

@interface SeparateDetailsViewController ()<SeparateDetailsCellDelegate>

@property (nonatomic, strong) NSArray *sections;

@property (nonatomic, strong) UIImageView *header;

@property (nonatomic, strong) UIView *footer;


@property (nonatomic, strong) ShopSeparateDetailModel *model;


@end

@implementation SeparateDetailsViewController


- (void)setupUI{
    
    {
        self.baseNavView.navTitleLabel.text = self.item.divisionPlanName;
        [self.header sd_setImageWithURL:[NSURL URLWithString:self.item.imgName] placeholderImage:[UIImage imageNamed:@"placeholder_large"]];
    }
}

- (void)setupLayout{
    
    self.reloadBtn.mj_y += 30;
    self.reloadLab.mj_y += 30;
}

#pragma mark - networking methods

- (void)initData{

    @weakify(self);
    [[[MeatShopApi sharedInstance] getShopSeparatePlanDetailByDivisionPlanId:self.item.divisionPlanId] subscribeNext:^(ShopSeparateDetailModel * _Nullable model) {
        @strongify(self);
        
        NSString *text = [NSString stringWithFormat:@"分割种类（%ld）", model.pigpositionList.count];
        self.sections = @[@"分割简介", text];

        self.model = model;
        if (self.isRefresh) {
            [self endRefresh];
        }
        
        if (self.model.pigpositionList.count >0) {
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }else{
            [self loadNoData];
        }
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}

//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
}

#pragma mark - 折叠按钮点击代理

- (void)clickFoldLabel:(SeparateDetailsCell *)cell{
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    PigpositionList *item = self.model.pigpositionList[indexPath.row];
    item.isOpening = !item.isOpening;
    
    [self.tableView beginUpdates];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
}


#pragma mark - tableview.delegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

#pragma mark - tableview.datascource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return section == 0 ?1 :self.model.pigpositionList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return self.item.cellHeight + 50;
    }
    
    if (self.model.pigpositionList.count > 0)
    {
        PigpositionList *item = self.model.pigpositionList[indexPath.row];

        if (item.isOpening) {
            // 使用不缓存的方式
            return [self.tableView fd_heightForCellWithIdentifier:rightCellIdentifier configuration:^(id cell) {
                
                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }else{
            // 使用缓存的方式
            return [self.tableView fd_heightForCellWithIdentifier:rightCellIdentifier cacheByIndexPath:indexPath configuration:^(id cell) {
                
                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }
    } else{
        
        return 10;
    }
}

// 处理折叠cell高度
-(void)handleCellHeightWithNewsCell:(id)cell indexPath:(NSIndexPath *)indexPath{
    
    SeparateDetailsCell *newsCell = (SeparateDetailsCell *)cell;
    PigpositionList *item = self.model.pigpositionList[indexPath.row];
    newsCell.item = item;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 34;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    EditShopSectionsView *view = [[EditShopSectionsView alloc] init];
    view.label.text = self.sections[section];
    
    CAShapeLayer *line = [CAShapeLayer layer];
    line.fillColor = mIconLineColor.CGColor;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 33.5, KScreenWidth, 0.5)];
    line.path = path.CGPath;
    [view.layer addSublayer:line];
    
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        SeparateContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SeparateContentCell"];
        cell.item = self.item;
        return cell;
    }

    
    PigpositionList *item = self.model.pigpositionList[indexPath.row];
    SeparateDetailsCell *newsCell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier];
    newsCell.cellDelegate = self;
    newsCell.item = item;

    return newsCell;
}


#pragma mark - setter methods

#pragma mark - getter methods

- (void)registerTableViewCell
{
    self.tableView.rowHeight = 100;
    self.tableView.height = KScreenHeight - TJ_NavBarHeight;
    self.tableView.mj_y = TJ_NavBarHeight;
    self.tableView.separatorColor = KClearColor;
    self.tableView.tableHeaderView = self.header;
    self.tableView.tableFooterView = self.footer;
    self.tableView.mj_footer.hidden = YES;
    [self.tableView registerClass:[SeparateDetailsCell class] forCellReuseIdentifier:rightCellIdentifier];
    [self.tableView registerClass:[SeparateContentCell class] forCellReuseIdentifier:@"SeparateContentCell"];
}


- (UIImageView *)header{
    
    if (!_header) {
        _header = [UIImageView new];
        _header.frame = CGRectMake(0, 0, KScreenWidth, 250);
        _header.image = [UIImage imageNamed:@"placeholder_large"];
    }
    return _header;
}


- (UIView *)footer{
    
    if (!_footer) {
        _footer = [UIView new];
        _footer.frame = CGRectMake(0, 0, KScreenWidth, 128);
        _footer.backgroundColor = mBackgroudColor;
        
        
        UIButton *button = [UIButton makeButtonWithText:@"确定" textColor:KWhiteColor font:mFont(16) textAliment:1 cornerRadius:5];
        [button setBackgroundImage:[UIImage imageNamed:@"btn_nomal_bg"] forState:UIControlStateNormal];
        button.frame = CGRectMake(15, 40, KScreenWidth - 30, 48);
        [_footer addSubview:button];
        
        @weakify(self);
        button.tapBlock = ^{
            @strongify(self);
            EditShopBox *box = [[EditShopBox alloc] init];
            box.dealOkBlock = ^{
                SeparatePlanViewController *vc = [[SeparatePlanViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            };
            [box showView];
        };
        
    }
    return _footer;
}


#pragma mark - other methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    CGFloat sectionHeaderHeight = 34;
    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

- (NSArray *)sections
{
    if (!_sections) {
        _sections = @[@"分割简介", @"分割种类（9）"];
    }
    return _sections;
}


#pragma mark override methods

- (void)loadErrorData
{
    [super loadErrorData];
    self.header.hidden = YES;
}

- (void)loadNoData
{
    [super loadNoData];
    self.header.hidden = YES;
}


- (void)endLoadMore{
    [super endLoadMore];
    self.header.hidden = NO;
}

- (void)endRefresh{
    [super endRefresh];
    self.header.hidden = NO;
    
}

- (void)endLoadMoreMoData
{
    [super endLoadMoreMoData];
    self.header.hidden = NO;
}


@end
